package l1j.opqlo.Timer.Controler;

import java.util.Collection;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.opqlo.Server.L1World.L1World;
import l1j.server.Thread.PcOtherThreadPool;
import l1j.server.server.model.Instance.L1PcInstance;

/**
 * PC EXP更新處理 時間軸
 *
 * @author dexc
 *
 */
public class ExpTimer extends TimerTask {

	private static final Logger _log = Logger.getLogger(ExpTimer.class
			.getName());

	/**
	 * 判斷
	 *
	 * @param tgpc
	 * @return true:執行 false:不執行
	 */
	private static boolean check(L1PcInstance tgpc) {
		try {

			if (tgpc == null) {
				return false;
			}

			if (tgpc.getOnlineStatus() == 0) {
				return false;
			}

			if (tgpc.getNetConnection() == null) {
				return false;
			}

			if (tgpc.isTeleport()) {
				return false;
			}

			if (tgpc.getExp() == tgpc.getExpo()) {
				return false;
			}

		} catch (final Exception e) {
			return false;
		}
		return true;
	}

	private ScheduledFuture<?> _timer;

	@Override
	public void run() {
		try {
			final Collection<L1PcInstance> all = L1World.getInstance().getAllPlayers();
			// 不包含元素
			if (all.isEmpty()) {
				return;
			}
			int i=0;
			for (final L1PcInstance tgpc : all) {
				tgpc.onChangeLawful();
				if (check(tgpc)) {
					tgpc.onChangeExp();
					i++;
					if(i % 3 ==0){ //執行三次休眠 1ms
						Thread.sleep(1);
					}
				}
			}

		} catch (final Exception e) {
			_log.log(Level.SEVERE, "EXP更新處理時間軸異常重啟", e);
			PcOtherThreadPool.get().cancel(this._timer, false);
			final ExpTimer expTimer = new ExpTimer();
			expTimer.start();
		}
	}

	public void start() {
		final int timeMillis = 500;
		this._timer = PcOtherThreadPool.get().scheduleAtFixedRate(this,timeMillis, timeMillis);
	}
}
